package com.heimo.agentlicence.http;

import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class HtmlHelper {
	private final static String CHARSET = "UTF-8";

//	public static NodeList getNodeList(String html) throws ParserException {
//		Parser parser = Parser.createParser(html, CHARSET);
//		NodeList list = null;
//		list = parser.parse(null);
//		return list;
//	}
//
//	public static NodeList getNodeListByTag(String html, String tag)
//			throws ParserException {
//		NodeList nodelist;
//		Parser parser = Parser.createParser(html, CHARSET);
//		NodeFilter filter = new TagNameFilter(tag);
//		nodelist = parser.parse(filter);
//		return nodelist;
//	}
//
//	public static NodeList getNodeListByClass(String html, Class filterClass)
//			throws ParserException {
//		NodeList list = null;
//		Parser parser = new Parser(html);
//		NodeFilter inputFilter = new NodeClassFilter(filterClass);
//		list = parser.parse(inputFilter);
//		return list;
//
//	}

	public static String getInputName(String result) {
		int startIndex = result.indexOf("name=\"") + 6;
		int endIndex = result.indexOf("\"", startIndex);
		return result.substring(startIndex, endIndex);
	}

	public static String getInputValue(String result) {
		int startIndex = result.indexOf("value=\"") + 7;
		int endIndex = result.indexOf("\"", startIndex);
		return result.substring(startIndex, endIndex);
	}

	public static void getAllInputAsNameValuePair(String html,
			List<NameValuePair> nvps) throws Exception {
		Document doc;
		try {
			doc = Jsoup.parse(html, CHARSET);
			Elements result = doc.select("input[id]");
			for (int i = 0; i < result.size(); i++) {
				Element e = result.get(i);
				if (e.attr("type") != null) {
					String name = e.attr("name");
					String val = e.val();
					if(name!=""){
						nvps.add(new BasicNameValuePair(name, val));
					}
				}
			}
		} catch (Exception e) {
			throw new Exception("Error parsing HTML data...");
		}
	}
}
